<template>
	<view class="">
		<wd-search v-model="searchValue" @search="handlesearch" hide-cancel placeholder-left placeholder="请输入关键字">
			<template #prefix>
				<wd-popover mode="menu" :content="menu" @menuclick="handleSearchChange">
					<view class="search-type">
						<text>{{ searchType }}</text>
						<wd-icon custom-class="icon-arrow" name="fill-arrow-down"></wd-icon>
					</view>
				</wd-popover>
			</template>
		</wd-search>
		<wd-message-box />
		<wd-toast />
		<wd-tabs v-model="activeTab" auto-line-width @change="handleTabChange">
			<wd-tab v-for="tab in tabs" :key="tab.value" :title="tab.label" :name="tab.value">
				<view class="px-1 py-1">
					<wd-table :data="list[tab.value]" :height="600" :border="false" @row-click="handleClick">
						<wd-table-col v-for="(col, index) in columns[tab.value]" :key="index" :prop="col.prop"
							:label="col.label" :width="col.width || '100'" :align="col.align || 'center'">
							<template #value="{ row }">
								<template v-if="col.prop.includes('.')">
									<!-- 如果是嵌套属性，拆分路径并按路径访问数据 -->
									{{ getNestedValue(row, col.prop) || '-' }}
								</template>
								<template v-else-if="col.isTag">
									<wd-tag custom-class="space"
										:type="col.color ? col.color(row[col.prop]) : 'primary'">
										{{ col.format ? (col.format(row[col.prop]) || '-') : (row[col.prop] || '-') }}
									</wd-tag>
								</template>
								<template v-else>
									{{ col.format ? (col.format(row[col.prop]) || '-') : (row[col.prop] || '-') }}
								</template>
							</template>
						</wd-table-col>
						<wd-table-col prop="grade" label="操作" width="200" fixed align="center">
							<template #value="{ row }">
								<text class="px-1 text-#4d80f0" @click.stop="handleProcessDetail(row)">
									查看
								</text>
								<text class="px-1 text-#4d80f0" v-if="row.status === 3"
									@click.stop="row.status === 3  ? handleAddOrEdit(row.id, true) : handleAddOrEdit(row.id)">
									{{ row.status === 0 ? '修改' :  row.status === 3 ? '重新填写' : ''
									}}
								</text>
								<text class="px-1 text-#4d80f0" @click.stop="handleDelete(row.id)">
									{{ row.status === 0 ? '取消' : '' }}
								</text>
								<text class="px-1 text-#4d80f0" @click.stop="handleExpedite(row)">
									{{ row.status !== 2 && row.status !== 4 ? '催办' : '' }}
								</text>
							</template>
						</wd-table-col>
					</wd-table>
				</view>
			</wd-tab>
		</wd-tabs>
		<Pagination :total="total" :pageNo="queryParams.pageNo" :pageSize="queryParams.pageSize"
			@update:pageNo="changePage" />
		<view class="mx-12 my-8 ">
			<up-button text="新增" color="#5ac725" shape="circle" @click="handleAddOrEdit()"></up-button>
		</view>
	</view>
</template>

<script setup lang="ts">
import { onShow } from '@dcloudio/uni-app'
import { ref, onMounted, nextTick } from 'vue'
import { DICT_TYPE, getIntDictOptions, getDictLabel, getDictColor } from '@/utils/dict'
import { getNestedValue } from '@/utils/fileUtils'
import { useMessage, useToast } from 'wot-design-uni'
import { LawsuitGeneralApi, LawsuitGeneralVO } from '@/api/legal/GeneralCase/lawsuitgeneral'
import { LawsuitResponseGeneralApi, LawsuitResponseGeneralVO } from '@/api/legal/GeneralCase/lawsuitresponsegeneral'
import * as TaskApi from '@/api/bpm/task'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import { formatPast2, formatDate } from '@/utils/formatTime'
import { expediting } from '@/utils/processinstance'


const message = useMessage()
const toast = useToast()

//存储数据
const list = ref<any>({
	lawsuitapproval: [],  // 一般起诉案件审批
	lawsuitdefense: [],   // 一般应诉案件审批
})
// 表单列配置项
const columns = {
	lawsuitapproval: [
		{ prop: 'caseUnit', label: '涉案单位', width: 160 },
		// { prop: 'charger', label: '负责人', width: 120 },
		// { prop: 'chargerContact', label: '负责人联系电话', width: 130 },
		// { prop: 'submitter', label: '资料提交人', width: 130 },
		// { prop: 'submitterContact', label: '资料提交人联系电话', width: 150 },
		{
			prop: 'status',
			label: '审批状态',
			align: 'center',
			width: 110,
			format: (val: any) => getDictLabel(DICT_TYPE.BPM_TASK_STATUS, val),
			color: (val: any) => getDictColor(DICT_TYPE.BPM_TASK_STATUS, val),
			isTag: true
		}

	],
	lawsuitdefense: [
		{ prop: 'defendant', label: '涉案单位', width: 160 },
		// { prop: 'charger', label: '负责人', width: 120 },
		// { prop: 'chargerContact', label: '负责人联系电话', width: 130 },
		// { prop: 'submitter', label: '资料提交人', width: 120 },
		// { prop: 'submitterContact', label: '资料提交人联系电话', width: 150 },
		{
			prop: 'status',
			label: '审批状态',
			align: 'center',
			width: 110,
			format: (val: any) => getDictLabel(DICT_TYPE.BPM_TASK_STATUS, val),
			color: (val: any) => getDictColor(DICT_TYPE.BPM_TASK_STATUS, val),
			isTag: true
		}

	]

} as any
const activeTab = ref('lawsuitapproval')
const tabs = ref([
	{
		label: '一般起诉案件审批',
		value: 'lawsuitapproval',
		api: LawsuitGeneralApi.getLawsuitGeneralPage,
	},
	{
		label: '一般应诉案件审批',
		value: 'lawsuitdefense',
		api: LawsuitResponseGeneralApi.getLawsuitResponseGeneralPage,
	}
])

// 查询参数
const queryParams = ref<any>({
	pageNo: 1,
	pageSize: 10,

	caseUnit: '',
	defendant: '',
	charger: '',

})
const total = ref(0)
const loading = ref(false)

const searchType = ref<string>('涉案单位')
const searchValue = ref<string>('')
const menu = ref<any[]>([
	{
		content: '涉案单位',
		prop: 'caseUnit'
	},
])
const handleTabChange = async (value: any) => {
	searchValue.value = ''
	queryParams.value.caseUnit = undefined;
	queryParams.value.defendant = undefined;
	await nextTick();
	fetchList();

}
function handleSearchChange({ item }: { item: any }) {
	searchType.value = item?.content
}
const handlesearch = () => {
	// 找到选中的搜索字段
	const selectedMenu = menu.value.find(item => item.content === searchType.value);
	if (selectedMenu) {
		// 清空之前的搜索条件
		queryParams.value.caseUnit = undefined;
		queryParams.value.defendant = undefined;
		// 根据选中的搜索类型设置搜索值
		if (activeTab.value === 'lawsuitapproval') {
			queryParams.value.caseUnit = searchValue.value.trim()
		} else {
			queryParams.value.defendant = searchValue.value.trim()
		}
		// queryParams.value[selectedMenu.prop] = value.value.trim();
		// 重新获取数据
		fetchList();
	}
};

// 切换分页
const changePage = (newPage: any) => {
	queryParams.value.pageNo = newPage
	fetchList()
}

// 获取单个 tab 数据
const fetchList = async () => {
	const currentTab = tabs.value.find(t => t.value === activeTab.value);
	if (!currentTab) return;

	loading.value = true;
	try {
		const response = await currentTab.api(queryParams.value);
		list.value[activeTab.value] = response.list
		console.log('list.value', list.value);
		total.value = response.total;
		for (let item of list.value[activeTab.value]) {
			item.status = item.isApproved === false ? 0 : item.status;
		}
		console.log('list.value', list.value);
	} catch (error) {
		console.error(error);
	} finally {
		loading.value = false;
	}
};



/** 查看详情页面 */
const handleProcessDetail = (row: any) => {
	let url = ''
	switch (activeTab.value) {
		case 'lawsuitapproval':
			url = `/pagesPackage/Legal/GeneralCase/lawsuitgeneral/detail?processInstanceId=${row.processInstanceId}&id=${row.id}`
			break
		case 'lawsuitdefense':
			url = `/pagesPackage/Legal/GeneralCase/lawsuitresponsegeneral/detail?processInstanceId=${row.processInstanceId}&id=${row.id}`
			break
	}

	uni.navigateTo({ url })
}
/** 点击一整行跳转至详情页面 */
const handleClick = ({ rowIndex }: any) => {
	handleProcessDetail(list.value[activeTab.value][rowIndex])

}
/** 新增或编辑页面 */
const handleAddOrEdit = (id?: any, resubmit = false) => {
	let url = ''
	switch (activeTab.value) {
		case 'lawsuitapproval':
			url = `/pagesPackage/Legal/GeneralCase/lawsuitgeneral/create`
			break
		case 'lawsuitdefense':
			url = `/pagesPackage/Legal/GeneralCase/lawsuitresponsegeneral/create`
			break
	}

	if (id) {
		if (resubmit === true) {
			console.log('resubmit', resubmit);
			url += `?id=${id}&resubmit=1`;
		}
		console.log('传过来的Id', id);
		url += `?id=${id}&resubmit=0`;
	} else {
		url += `?resubmit=0`;
	}

	uni.navigateTo({ url })
}

/** 删除操作 */
const handleDelete = async (id: number) => {
	try {
		await message.confirm({
			msg: '您确定要取消吗？',
			title: '提示',
		})

		const apiMap: Record<string, Function> = {
			lawsuitapproval: LawsuitGeneralApi.deleteLawsuitGeneral,
			lawsuitdefense: LawsuitResponseGeneralApi.deleteLawsuitResponseGeneral,

		}

		const api = apiMap[activeTab.value]
		if (!api) throw new Error('未找到对应 API')

		await api(id)
		toast.success('取消成功')
		await fetchList()
	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
/**催办 */
const handleExpedite = (row: any) => {
	expediting({
		processInstanceId: row.processInstanceId,
		processName: '青运-法务审批-合同审核'
	})
}
// 生命周期
onMounted(() => {
	fetchList()
})
onShow(() => {
	fetchList()
})
</script>

<style scoped lang="scss"></style>